package com.itheima.health.task;

import com.aliyun.oss.model.OSSObjectSummary;
import com.itheima.health.service.impl.SetMealServiceImpl;
import com.itheima.health.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
public class OSSDeleteTask {

    private final AliOssUtil aliOssUtil;
    private final SetMealServiceImpl setMealServiceImpl;

    public OSSDeleteTask(AliOssUtil aliOssUtil, SetMealServiceImpl setMealServiceImpl) {
        this.aliOssUtil = aliOssUtil;
        this.setMealServiceImpl = setMealServiceImpl;
    }

    /**
     * 定时任务 ，每月1日执行一次
     */
//    @Scheduled(cron = "0 0 0 1 * ?")
    @Scheduled(cron = "0 52 * * * ?")
    public void delete() {
        log.info("定时删除冗余图片数据");
        //获取oss图片数据
        List<OSSObjectSummary> ossObjectSummaries = aliOssUtil.selectList(1000);

        //获取数据库图片数据
        List<String> saveimgs = setMealServiceImpl.selectImgs();

        //遍历查询所有不被数据库中图片包含的资源，然后删除
        ossObjectSummaries.forEach(ossObjectSummary -> {
            log.info("oss 图片资源名称：{}",ossObjectSummary.getKey());
            if (!saveimgs.contains(ossObjectSummary.getKey())) {
                aliOssUtil.deleteFile(ossObjectSummary.getKey());
            }
        });

    }
}
